import { dataContainer } from "./lib/service";
import EPGItem from "./lib/epgItem";
import EPGGroup from "./lib/epgGroup";
import * as epgService from "./lib/service";
import * as keyActions from "./lib/keyActions";
import { selfLog } from "./lib/utils";

const _directive = (beforeMount, mounted, updated, unmounted) => {
  return {
    beforeMount: beforeMount,
    mounted: mounted,
    updated: updated,
    unmounted: unmounted,
  };
};

export default {
  install(app) {
    const groupBeforeMount = (el, binding, vnode) => { };
    const groupMounted = (el, binding, vnode) => {
      let group = new EPGGroup(vnode, binding);
      epgService.registerGroup(group);
    };
    const groupUpdated = (el, binding, vnode) => {
      let item = new EPGGroup(vnode, binding);
      epgService.updateGroup(item);
    };
    const groupUnmount = (el, binding, vnode) => {
      const index = dataContainer.groupArray.findIndex(
        (item) => item.id === el.dataset.epgGroupId
      );
      dataContainer.groupArray.splice(index, 1);
    };
    app.directive(
      "epg-group",
      _directive(groupBeforeMount, groupMounted, groupUpdated, groupUnmount)
    );
    const itemBeforeMount = (el, binding, vnode) => { };
    const itemMounted = (el, binding, vnode) => {
      let item = new EPGItem(vnode, binding);
      epgService.registerItem(item);
    };
    const itemsUpdated = (el, binding, vnode) => {
      let item = new EPGItem(vnode, binding);
      epgService.updateItem(item);
    };
    const itemUnmounted = (el, binding, vnode) => {
      const index = dataContainer.itemArray.findIndex((item) => {
        if (dataContainer.currentItem) {
          if (dataContainer.currentItem.id === el.dataset.epgItemId) {
            selfLog("当前元素已经卸载，移除 CurrentItem");
            dataContainer.currentItem = null;
          }
        }
        return item.id === el.dataset.epgItemId;
      });
      if (index != -1) {
        dataContainer.itemArray.splice(index, 1);
      }
    };
    app.directive(
      "epg-item",
      _directive(itemBeforeMount, itemMounted, itemsUpdated, itemUnmounted)
    );
    app.provide("epg", epgService);
  },
};

export const useVuEPG = () => {
  return { ...epgService, ...keyActions };
};
